<template>
  <div class="main" style="height: 100%">
    <div>
      <div class="topSearch" v-if="false">
        <!-- <span>
          报销一级分类:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择一级分类"
            v-model="params.financeId"
          >
            <el-option
              v-for="(e, i) in oneType"
              :label="e.financeName"
              :key="i"
              :value="e.financeId"
            ></el-option>
          </el-select>
        </span>
        <span>
          报销二级分类:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择二级分类"
            v-model="params.financeLevelTypeId"
          >
            <el-option
              v-for="(e, i) in twoType"
              :label="e.levelName"
              :key="i"
              :value="e.id"
            ></el-option>
          </el-select>
        </span>
        <span>
          仓库:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择仓库名称"
            v-model="params.areaId"
          >
            <el-option
              v-for="(e, i) in areaData"
              :label="e.areaName"
              :key="i"
              :value="e.area"
            ></el-option>
          </el-select>
        </span>
        <span>
          品牌:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择品牌"
            v-model="params.systemType"
          >
            <el-option
              :value="item.id"
              :label="item.systemName"
              :key="item.id"
              v-for="item in systemList"
            ></el-option>
          </el-select>
        </span>
        <span>
          接收回款方式:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="接收回款方式"
            v-model="params.paymentMethod"
          >
            <el-option
              v-for="(e, i) in paymentMethodData"
              :label="e.name"
              :key="i"
              :value="e.value"
            ></el-option>
          </el-select>
        </span> -->
        <!-- <span>
          报销状态:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder=" 报销状态"
            v-model="params.status"
          >
            <el-option
              v-for="(e, i) in baoXiaoStatus"
              :label="e.name"
              :key="i"
              :value="e.value"
            ></el-option>
          </el-select>
        </span> -->
        <!-- <span>
          责任主体:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder=" 责任主体"
            v-model="params.operator"
          >
            <el-option
              v-for="(e, i) in responsibility"
              :label="e.optionerName"
              :key="i"
              :value="e.id"
            ></el-option>
          </el-select>
        </span>
        <span>
          报销接收人:
          <el-select
            size="small"
            style="width: 230px"
            placeholder="请选择报销接收人"
            v-model="params.reimburseRecipient"
          >
            <el-option
              :label="item.userName"
              :value="item.userName"
              :key="item.id"
              v-for="item in receiveData"
            ></el-option>
          </el-select>
        </span> -->
        <span>
          <!-- <el-button size="mini" type="primary" @click="searchList"
            >查询</el-button
          > -->
          <!-- <el-button size="mini" type="primary" @click="addReimburse">
            新增报销
          </el-button> -->
          <!-- <el-button size="mini" type="primary" @click="_addStore"
            >录入门店
          </el-button> -->
        </span>
      </div>
    </div>
    <div style="margin-top: 20px">
      <el-table
        :data="dataList"
        :height="maxHeight"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        show-overflow-tooltip
        tripe
        border
        tooltip-effect="dark"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
        :cellStyle="{
          textAlign: 'center',
          fontSize: '12px',
        }"
      >
        <el-table-column prop="id" label="id" width="100px"></el-table-column>
        <el-table-column
          label="责任主体名称"
          prop="optionerName"
          min-width="200px"
        >
        </el-table-column>

        <el-table-column label="明细操作" width="180px" fixed="right">
          <template slot-scope="scope">
            <el-link
              type="primary"
              v-if="authority.includes(1055)"
              @click="review(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >报销原因列表
            </el-link>
            <!-- <el-link
              type="primary"
              v-if="scope.row.status === 0"
              @click="review(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >审核
            </el-link>
            <el-link
              type="warning"
              v-if="scope.row.status === 1"
              @click="transferFunds(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >打款
            </el-link>
            <el-link
              v-if="scope.row.status === 0"
              type="info"
              @click="cancelItem(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >取消
            </el-link>
            <el-link
              type="danger"
              @click="deteItme(scope.row)"
              v-prevent-re-click
              >删除</el-link
            > -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div style="padding-top: 20px">
      <el-pagination
        style="border-top: 1px solid #eee; padding-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNumber"
        :page-sizes="[20, 30, 50]"
        :page-size="20"
        layout="total, sizes, prev, pager, next, jumper"
        align="right"
        :total="params.totalCount"
      >
      </el-pagination>
    </div> -->
    <el-dialog
      :close-on-click-modal="false"
      title="报销原因类型"
      :visible.sync="ledgerStatus"
      width="80%"
      center
      :show-close="false"
      top="10px"
      :before-close="handleClose"
    >
      <el-button size="mini" @click="autab(1, '')"  v-if="authority.includes(1056)" type="primary"
        >新增原因类型</el-button
      >
      <div class="feeTable">
        <el-table
          :data="twoTypeTable"
          @selection-change="handleSelectionChange"
          style="margin-top: 10px"
          border
          :headerCellStyle="{
            textAlign: 'center',
            fontWeight: 400,
            background: '#66b1ff',
            color: 'white',
          }"
          :cellStyle="{
            textAlign: 'center',
            fontSize: '12px',
          }"
        >
          <el-table-column prop="id" label="ID" width="70px"></el-table-column>
          <el-table-column
            prop="reimburseType"
            label="报销原因类型"
          ></el-table-column>

          <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
              <el-link
                type="warning"
                @click="autab(2, scope.row)"
                v-prevent-re-click
                v-if="authority.includes(1057)"
                style="margin-right: 10px"
                >编辑
              </el-link>
              <el-link
                type="danger"
                v-if="authority.includes(1058)"
                @click="deteItme(scope.row)"
                v-prevent-re-click
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ledgerStatus = false">返 回</el-button>
      </span>

      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="erAddUpDialog"
        center
        append-to-body
        :title="erAddUpTitle"
        width="30%"
      >
        名称：
        <el-input
          size="small"
          style="width: 280px"
          v-model="erFenObj.reimburseType"
        ></el-input>
        <span slot="footer">
          <el-button @click="erAddUpDialog = false">取 消</el-button>
          <el-button type="primary" @click="comfirmClose">确定</el-button>
        </span>
      </el-dialog>
    </el-dialog>

    <add-reimburseNew
      ref="addDialog"
      @addStatus="receiveMessage"
    ></add-reimburseNew>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="closeDialog"
      center
      title="选择日期"
      width="30%"
    >
      日期：
      <el-date-picker
        v-model="time"
        type="date"
        size="small"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        style="width: 80%"
        placeholder="选择日期"
      >
      </el-date-picker>
      <span slot="footer">
        <el-button @click="closeDialog = false">取 消</el-button>
        <el-button type="primary" @click="comfirmClose">确定</el-button>
      </span>
      <span slot="footer" class="dialog-footer">
        <span style="display: block; color: red"
          >*确定后该日期前的订单不可再继续报销</span
        >
      </span>
    </el-dialog>

    <div>
      <el-dialog
        :visible.sync="dialogAddStore"
        :close-on-click-modal="false"
        title="录入门店"
        top="10px"
        height="calc(100vh - 350px)"
        style="overflow-y: auto"
        width="40%"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <span style="width: 80px">店铺名称：</span>
              <el-input
                size="small"
                style="width: 280px"
                v-model="storeObj.storeName"
              ></el-input>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <span style="width: 80px">订单类型：</span>
              <el-select
                size="small"
                style="width: 280px"
                placeholder="请选择订单类型"
                v-model.number="storeObj.systemType"
              >
                <el-option
                  v-for="(item, index) in systemList"
                  :key="index"
                  :label="item.systemName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col
              :span="12"
              style="display: flex; flex-direction: row; align-items: center"
            >
              <span style="width: 80px">店铺地址：</span>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="storeObj.address"
              ></el-input>
            </el-col>
          </el-row>
        </div>
        <span slot="footer">
          <el-button @click="dialogAddStore = false">取 消</el-button>
          <el-button type="primary" @click="_submitStore">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import upload from '@/RayComponents/upload.vue'
import dayjs from 'dayjs'
import axios from 'axios'
import Decimal from 'decimal.js'
import addReimburseNew from './addReimburseNew.vue'
import quinn from '../../../utils/quinn'
import store from '../../../store'
import ExcelJS from 'exceljs'
import checkDetail from './checkDetail.vue'

export default {
  name: 'reimbursementPeople',
  components: {
    upload,
    addReimburseNew,
    checkDetail,
  },
  data() {
    return {
      selectOneId: null,
      erFenObj: {
        reimburseType: '',
        optionerId: null,
        id: null,
      },

      erAddUpDialog: false,
      erAddUpTitle: '新增分类',
      twoTypeTable: [],
      siTongguo: null,
      receiveData: [], //报销接收人
      responsibility: [], //责任主体
      oneType: [],
      twoType: [],
      paymentMethodData: [
        { value: 1, name: '银行卡' },
        { value: 2, name: '微信' },
        { value: 3, name: '支付宝' },
      ],

      areaData: [],
      apiName: 'newAreaLedgerList',
      params: {
        pageNumber: 1,
        pageSize: 20,
        financeId: null,
        financeLevelTypeId: null,
        areaId: null,
        systemType: null,
        status: null, //报销状态
        paymentMethod: null, //接受回款方式
        operator: '', //责任主体
        reimburseRecipient: null, //报销接收人
      },
      payUrl: '',
      previewPayList: [],
      innerVisible: false,
      buttonShow: false,
      closeDialog: false,
      rejectDialog: false,
      loading: false,
      visible: false,
      innerTitle: '',
      cardNo: '',
      rejectId: {},
      paidUrl: [],
      cardName: '',
      userName: '',
      bankName: '',
      totalCount: 0,
      previewImg: [],
      host: this.$imgHost,
      previewImgList: [],
      systemList: [],
      chooseDateIndex: 1,
      dialogTitle: '',
      rejectReason: '',
      decimalCount: '',
      resFee: '',
      ledgerStatus: false,
      maxHeight: 0,
      typeOptions: [],
      typeList: [],
      createForm: {
        typeId: '',
        provinceId: '',
        voucher: '',
        price: '',
        remark: '',
      },
      orderId: '',
      time: '',
      provinceOptions: [],
      dataList: [],
      authority: [],
      feeData: [],
      arr: [],
      creatorList: [],
      storeObj: {
        storeName: '',
        systemType: null, //"系统订单类型   1 零食很忙订单 2 零食优选订单 3卡游 4冰杯订单 5派特 6唐饱饱 7零食很嗨 8动感生活
        address: '', //门店地址
      },
      dialogAddStore: false,
    }
  },
  watch: {},
  computed: {
    preImgs() {
      return this.paidUrl.map((e) => `${this.$imgHost}${e}`)
    },
    headers() {
      const token = this.token || this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  created() {
    const {authorityList = []} = quinn.getStorage('userData')
    this.authority = authorityList
    // this.$api.areaLedgerAreaList().then((res) => {
    //   this.areaData = res
    // })
    // this.$api.financeOneType().then((res) => {
    //   this.oneType = res
    // })
    // this.$api.financeTwoType().then((res) => {
    //   this.twoType = res
    // })
    // this.$api.financeGetOptionerType().then((res) => {
    //   this.responsibility = res
    // })
    // // 报销接收人
    // this.$api
    //   .getAccount({
    //     pageSize: 100000,
    //     pageNumber: 1,
    //   })
    //   .then((res) => {
    //     if (res && res.data) {
    //       this.receiveData = []
    //       this.receiveData = res.data
    //     }
    //   })
    this.getList()
  },
  mounted() {
    // this.getProvince()

    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 340
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 340
      })
    }
  },
  methods: {
    getErTypeByOneId() {
      this.$api
        .financeGetReimburseTypeByOid({ optionerId: this.selectOneId })
        .then((res) => {
          console.log('联动出的报销原因', res)
          this.twoTypeTable = res
        })
    },
    autab(type, val) {
      if (type == 1) {
        this.erAddUpTitle = '新增原因类型'
        this.erFenObj.reimburseType = ''
        this.erFenObj.optionerId = this.selectOneId
        this.erFenObj.id = null
      } else {
        this.erAddUpTitle = '编辑原因类型'
        this.erFenObj.reimburseType = val.reimburseType
        this.erFenObj.optionerId = this.selectOneId
        this.erFenObj.id = val.id
      }
      this.erAddUpDialog = true
    },
    async _submitStore() {
      try {
        if (!this.storeObj.storeName) {
          return this.$message.warning('请输入门店名称！')
        }
        if (!this.storeObj.systemType) {
          return this.$message.warning('请选择订单类型！')
        }
        if (!this.storeObj.address) {
          return this.$message.warning('请输入门店地址！')
        }
        this.$api.orderInsertStoreInfo(this.storeObj).then((res) => {
          console.log('录入门店订单', res)
          if (res == 1) {
            this.$message.success(`新增成功！`)
            this.dialogAddStore = false
            this.getData()
          }
        })
      } catch {
        console.error('接口请求出错：', err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    _addStore() {
      this.storeObj.storeName = ''
      this.storeObj.address = ''
      this.storeObj.systemType = null
      this.dialogAddStore = true
    },
    cancelItem(row) {
      this.$confirm('确认要取消吗？')
        .then((_) => {
          // this.$api.orderUpdatePayStatus(data).then()
          this.$api
            .financeUpdateFinanceDataReimburseStatus({ id: row.id, status: 2 })
            .then((res) => {
              if (res == 1) {
                this.$message({ message: '操作成功!', type: 'success' })
                this.getList()
              }
            })
        })
        .catch((_) => {
          return
        })
    },
    transferFunds(row) {
      this.$confirm('确认要打款吗？')
        .then((_) => {
          // this.$api.orderUpdatePayStatus(data).then()
          this.$api
            .financeUpdateFinanceDataReimburseStatus({ id: row.id, status: 4 })
            .then((res) => {
              if (res == 1) {
                this.$message({ message: '操作成功!', type: 'success' })
                this.getList()
              }
            })
        })
        .catch((_) => {
          return
        })
    },
    review(val) {
      this.selectOneId = val.id
      this.getErTypeByOneId()
      this.ledgerStatus = true
    },
    deteItme(val) {
      this.$confirm('确认要删除吗？')
        .then((_) => {
          this.$api
            .financeDeleteReimburseType({
              id: val.id,
            })
            .then((res) => {
              if (res) {
                this.$message.success('操作成功！')
                this.getErTypeByOneId()
              }
            })
        })
        .catch((_) => {
          return
        })
    },
    checkDetail(val) {
      this.$refs.checkDetailRef.handleOpen(val)
    },
    getSystemType() {
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemList = res
      })
    },
    reject(row) {
      // this.rejectDialog = true
      // this.rejectReason = ''
      // this.rejectId = row
    },
    editAudit(row) {
      const data = {
        ...row,
        orderName: this.dialogTitle,
        orderId: this.orderId,
      }
      this.$refs.addDialog.handleOpen(data)
    },
    getStatusColor(status) {
      return status === 1
        ? 'orange'
        : status === 2
        ? '#66b1ff'
        : status === 0
        ? 'red'
        : 'transparent'
    },
    getLineColor(status) {
      return status === 1
        ? '1px solid orange'
        : status === 2
        ? '1px solid #66b1ff'
        : status === 0
        ? '1px solid red'
        : 'transparent'
    },
    isRowSelectable(row) {
      return row.status == 4
    },
    wareHousePass(row) {
      this.$api
        .storeLedgerUpdateSupervisorStatus({ storeLedgerId: row.id })
        .then((res) => {
          if (res == 1) {
            this.$message.success('操作成功！')
            this.chooseType(this.chooseDateIndex)
            // this.ledgerStatus=false
            this.getList()
          }
        })
    },
    remoteMethod(val) {
      if (val) {
        const params = {
          accountName: val,
        }
        this.$api.storeLedgerGetAccountName(params).then((res) => {
          this.creatorList = res
        })
      }
    },
    receiveMessage(val) {
      if (val == 1) {
        this.getList()
      }
      if (val == 2) {
        this.$api
          .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
          .then((res) => {
            this.typeList = res
          })
        this.chooseType(this.chooseDateIndex)
        this.getList()
      }
    },
    addReimburse() {
      this.$refs.addDialog.handleOpen()
    },
    closeReimburse() {
      this.closeDialog = true
      this.time = ''
    },
    comfirmClose() {
      if (this.erAddUpTitle === '新增原因类型') {
        //新增
        this.$api.financeAddReimburseType(this.erFenObj).then((res) => {
          console.log('新增', res)
          if (res == 1) {
            this.$message.success('新增成功！')
            this.getErTypeByOneId()
            this.erAddUpDialog = false
          }
        })
      } else {
        //编辑
        this.$api.financeUpdateReimburseType(this.erFenObj).then((res) => {
          console.log('编辑', res)
          if (res == 1) {
            this.$message.success('编辑成功！')
            this.getErTypeByOneId()
            this.erAddUpDialog = false
          }
        })
      }
    },
    handleSelectionChange(e) {
      if (e.toString()) {
        this.buttonShow = true
      } else {
        this.buttonShow = false
      }
      const _arr = e.map((el) => el.id)
      this.arr = _arr
    },

    deletePaiedUrl(i) {
      this.paidUrl.splice(i, 1)
    },
    onSuccess(res) {
      console.log(res)
      const { paidUrl = [] } = this
      if (res.code == 200 && res.result) {
        // paidUrl.push(res.result[0]);
        this.paidUrl = res.result
      }
    },
    confirmOrder(val) {
      this.$api.storeLedgerUpdateStoreLedgerStatus({ id: val }).then((res) => {
        this.getList()
      })
    },
    searchList() {
      this.params.pageNumber = 1
      this.getList()
    },
    getList() {
      this.loading = true
      this.$api.financeGetOptionerType().then((res) => {
        console.log('责任主体', res)

        this.dataList = res
        this.loading = false
      })
    },
    getProvince() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.provinceOptions = res
      })
    },

    handleSizeChange(e) {
      this.params.pageSize = e
      this.getList()
    },
    handleCurrentChange(e) {
      this.params.pageNumber = e
      this.getList()
    },
    async openDialog(row) {
      this.dialogTitle = row.storeName
      this.orderId = row.orderId
      const res = await this.$api
        .storeLedgerGetFinanceOneLevelTypeDto({ orderId: row.orderId })
        .then()
      const resFee = await this.$api
        .orderGetOrderExpressCharge({ orderId: row.orderId })
        .then()
      this.resFee = resFee
      if (resFee) {
        const decimalCount = new Decimal(resFee).div(new Decimal(4))
        this.decimalCount = decimalCount
      }
      this.typeList = res
      this.chooseType(this.chooseDateIndex)
      this.ledgerStatus = true
    },
    handleClose() {},

    comfirmAudit(val, type) {
      const data = {
        status: 1,
        id: val.id,
        rejectReason: this.rejectReason,
      }
      if (type == 3) {
        data.status = 0
        delete data.rejectReason
      }
      this.$api.storeLedgerUpdateStoreLedgerFinanceStatus(data).then((res) => {
        if (res == 1) {
          this.$message({ message: '操作成功!', type: 'success' })
          this.$api
            .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
            .then((res) => {
              this.typeList = res
            })
          this.chooseType(this.chooseDateIndex)
          this.rejectDialog = false
          this.getList()
        }
      })
    },

    checkPayType(val) {
      this.payId = val.id
      this.innerVisible = true
      this.paidUrl = []
    },
    async comfirmPay() {},
    //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线
    async deleteAudit(row) {
      const r = await this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => null)
      if (r) {
        const res = await this.$api
          .storeLedgerDeleteOrUpdateStoreLedger({ id: row.id })
          .catch(() => null)
        if (res == 1) {
          this.$message.success('操作成功!')
          this.chooseType(this.chooseDateIndex)
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;

  span {
    display: inline-block;
    width: 90px;
  }
}
.topSearch {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  span {
    display: inline-block;
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

.amountContainer {
  width: 100%;
  text-align: center;
}

.amountContainer > div:nth-child(1) {
  margin-bottom: 10px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.feeType {
  display: flex;
  justify-content: center;
}

.typeList {
  width: 150px;
  height: 60px;
  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  background: linear-gradient(to left, #b3d8ff, #b3d8ff) left top no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) left top no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right top no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) right top no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) left bottom no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) left bottom no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat;
  background-size: 1px 20px, 20px 1px, 1px 20px, 20px 1px;

  span {
    cursor: default;
  }
}

.active {
  box-shadow: inset 0 0 16px 0 #66b1ff;
  font-size: 16px;
  font-weight: bolder;
}
</style>
